# -*- coding: utf-8 -*-
import requests

import urllib.request
import string
import urllib.parse
import re


from bs4 import BeautifulSoup
import random

def format_url(url, params: dict=None) -> str:
    query_str = urllib.parse.urlencode(params)
    return f'{ url }{ query_str }'

def get_url(keyword):
    params = {
        'word': str(keyword)
    }
    url = "http://zhidao.baidu.com/q?ct=17&pn=0&tn=ikaslist&rn=10&fr=wwwt&"
    url = format_url(url, params)
    # print(url)

    return url

def get_page(url):
    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'host':'zhidao.baidu.com',
            'refer':url,
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
        }
        response = requests.get(url=url,headers=headers)
        # 更改编码方式，否则会出现乱码的情况
        response.encoding = "gbk"
        # print(response.text)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None
    
def baidu_search(keyword):
    url = get_url(keyword)
    html =get_page(url)
    soup = BeautifulSoup(html, 'html.parser')
    contents=soup.find("div",class_="list",id="wgt-list").findAll("a",class_="ti")
    size = len(contents)
    if size>3:
        size = 3
    index = random.randint(0,size-1)
    if size:
        url = contents[index].attrs['href']
        #print(url)
        html2 =get_page(url)
        soup2 = BeautifulSoup(html2, 'html.parser')
        answer = soup2.find("div",class_="best-text mb-10")
        if answer == None:
            answer = soup2.find("div",class_="answer-text mb-10 line")
        if answer == None:
            return ''
        result = ""
        for x in answer:
            word = re.sub(re.compile(r">\d{4}<"),'',str(x))
            word = re.sub(re.compile(r"<(.+?)>"),'',word)
            words = re.sub(re.compile(r"\[(.+?)\]"),'',word)
            #print(words,'\n')
            content = words.strip()
            if len(content):
                result+=content
        result = result.replace('展开全部','').replace('百度知道','我这')
        result = re.sub(re.compile(r"d{4}"),'',result)
        return result
    else:
        return ''

def replace(s,re_exp,repl_string):
    return re_exp.sub(repl_string,s)
    
def getAnswer(question):
    content = baidu_search(question)
    return content

'''while(True):        
    print("输入:")
    userinput = input("")
    print(getAnswer(userinput))'''

